/*
自己选择的路 ,跪着也要走完。朋友们 , 虽然这个世界日益浮躁起来,只
要能够为了当时纯粹的梦想和感动坚持努力下去 , 不管其它人怎么样,我
们也能够保持自己的本色走下去。
To the world , you will be a person , but to a person , you
will be the world .                               ——AKPower
*/
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
#include <queue>
#include <cstdio>
#include <string>
#include <stack>
#include <set>
#define IOS ios::sync_with_stdio(false), cin.tie(0)
using namespace std;
typedef long long ll;
ll f[66];
void init()
{
    f[0] = 1;
    for (int i = 1; i <= 60; i++)
    {
        f[i] = f[i - 1] * 2ll;
    }
}
int main()
{
    IOS;
    init();
    int t;
    cin >> t;

    while (t--)
    {
        ll n, m;
        cin >> n >> m;
        ll ans = 0;
        m = min(m, 60ll);
        for (int i = m; i >= 0; i--)
        {
            if (n == 0)
                break;
            ans += n / f[i];
            n %= f[i];
        }
        cout << ans << endl;
    }

    getchar();
    getchar();
    return 0;
}
